package cn.itcast.gateway.auth;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
* 定义一个全局过滤器
* */
//@Order(-1)//-1表示优先级最高 默认过滤器为1,或者Ordered
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
       ServerHttpResponse response=  exchange.getResponse();
      String authorization= request.getQueryParams().getFirst("authorization");

        // 对请求的参数判断是否合法
        //若参数不存在，或者存在但是不等于“admin”也不合法,再次过滤器截止
        if(StringUtils.isEmpty(authorization)||!"admin".equals(authorization)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //如果合法就放行给下一个过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
